//
//  CategoryGoodsViewController.m
//  B2C
//
//  Created by 冯琰琰 on 5/8/2018.
//  Copyright © 2018 lixiaolong. All rights reserved.
//

#import "CategoryGoodsViewController.h"
#import "ClassifyItemCell.h"
#import "ClassifyFirstModel.h"
#import "ClassifySecondModel.h"
#import "SearchCacheViewController.h"   // 跳转
#import "ClassifyDetailViewController.h" // 跳转
#import "FyClassTitleView.h" // TitleView
#import "ClassifyDetailItemModel.h"
#import "CommodityModel.h"


@interface CategoryGoodsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) FyClassTitleView *titleView;
@property (nonatomic, strong) NSMutableArray *GoodsArray;
@property (nonatomic, strong) NSMutableArray *secondArray;
@property (nonatomic, assign) NSInteger index;
@end

@implementation CategoryGoodsViewController
#pragma mark - viewController
- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        _GoodsArray = [NSMutableArray array];
        _secondArray = [NSMutableArray array];
        _index = 0;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1];
    [self configureUI];
}

-(void)setModel:(ClassifyFirstModel *)Model{
    _Model = Model;
    [self loadNetWork];
}

- (void)configureUI {
    [self.view addSubview:self.titleView];
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(1);
        make.height.mas_equalTo(52);
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(5);
        make.right.equalTo(self.view).offset(-5);
        make.bottom.equalTo(self.view);
        make.top.equalTo(_titleView.mas_bottom).offset(5);
    }];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.titleView = self.searchView;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self setBtnWithImage:@"category_selected" selectedImage:@"category_selected"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self setBtnWithImage:@"category_msg" selectedImage:@"category_msg"]];
}
- (void)reloadUI {
    [self.collectionView reloadData];
}

- (NSMutableArray *)getFirstStr:(NSArray *)arr {
    NSMutableArray *firstArr = [NSMutableArray array];
    for (ClassifyFirstModel *model in self.GoodsArray) {
        [firstArr addObject:model.gcname];
    }
    return firstArr;
}

#pragma mark - NetWork
- (void)loadNetWork {
    [self getSecondClass:self.Model.gcid];
}
- (void)getSecondClass:(NSString *)gcid {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:gcid forKey:@"gcid"];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goodstwoclass parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            NSMutableArray *secondArr = [NSMutableArray array];
            for (NSDictionary *modelDic in data) {
                ClassifySecondModel *model = [ClassifySecondModel mj_objectWithKeyValues:modelDic];
                [weakSelf.secondArray addObject:model];
            }
            [weakSelf getGoodsListWithSecondCategory:weakSelf.secondArray[0] item:nil];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
    }];
}

-(void)getGoodsListWithSecondCategory:(ClassifySecondModel *)secondModel item:(ClassifyDetailItemModel *)itemModel{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:secondModel.gtcid forKey:@"gtcid"];
    [parameters safeSetObject:itemModel.pageNationModel ? @(itemModel.pageNationModel.pageNumber) : @"1" forKey:@"pageNumber"];
    [parameters safeSetObject:@"10" forKey:@"pageSize"];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goods parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            NSDictionary *pagenation = [responseDic safeJsonObjectForKey:@"pagenation"];
            PageNationModel *pageNationModel = [PageNationModel mj_objectWithKeyValues:pagenation];
            NSMutableArray *dataArr = [NSMutableArray array];
            
            for (NSDictionary *modelDic in data) {
                CommodityModel *model = [CommodityModel mj_objectWithKeyValues:modelDic];
                [dataArr addObject:model];
            }
//            [weakSelf setDataToArr:dataArr withNationModel:pageNationModel Index:index withCell:cell];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
        
    } isNeedCache:NO];
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.GoodsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ClassifyItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ClassifyItemCell" forIndexPath:indexPath];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((ScreenWidth - 15)/2, 250 * ScreenWidth/375);
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    [self.navigationController pushViewController:searchCacheVC animated:YES];
    
    return NO;
}
-(UIButton *)setBtnWithImage:(NSString *)imageName selectedImage:(NSString *)selectedImage{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selectedImage] forState:UIControlStateSelected];
    [btn setTitleColor:[UIColor colorWithHex:0x333333 alpha:1] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHex:0x7abe45 alpha:1] forState:UIControlStateSelected];
    return btn;
}
#pragma mark - Getters
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-80, 36)];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        [_searchBar changeLeftPlaceholder:@"搜索美食"];
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 36;
        searchField.font = TextNormalFontSize(14);
    }
    return _searchBar;
}
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-80, 36)];
        [_searchView setBackgroundColor:[UIColor whiteColor]];
        [_searchView addSubview:self.searchBar];
    }
    return _searchView;
}
-(FyClassTitleView *)titleView{
    if (!_titleView) {
        NSArray *infoArray = [NSArray arrayWithObjects:@{@"title":@"综合",@"image":@" "},@{@"title":@"销量",@"image":@"category_lineView"},@{@"title":@"价格",@"image":@"category_lineView"}, nil];
        _titleView = [[FyClassTitleView alloc]initWithFrame:CGRectMake(0, 1, ScreenWidth, 51) btnInfoArray:infoArray];
    }
    return  _titleView;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 5 ;
        flowLayout.minimumLineSpacing = 5 ;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; // 纵向
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:248/255.0];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.bounces = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"ClassifyItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ClassifyItemCell"];
    }
    return _collectionView;
}
@end
